#include <stdlib.h>
#include <stdio.h>

#include "../../include/pqueue.h"

static void print_pqueue(const pqueue_t *pqueue)
{
	int idx;

	fprintf(stdout, "pqueue size is %d\n", pqueue->size);

	for (idx = 0; idx < pqueue_size(pqueue); idx++)
		fprintf(stdout, "node[%d] = %d\n", idx, *(int *)pqueue->tree[idx]);

	return;
}


static int compare_int(const void *key1, const void *key2)
{
	if (*(int *)key1 > *(int *)key2)
		return 1;

	if (*(int *)key1 < *(int *)key2)
		return -1;
	else
		return 0;
}

int main(int argc, char *argv[])
{
	pqueue_t pqueue;
	void	*data;
	int		intval[30],
			i;

	pqueue_init(&pqueue, compare_int, NULL);

	i = 0;

	intval[i] = 5;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	intval[i] = 10;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	intval[i] = 20;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	intval[i] = 1;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	intval[i] = 25;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	intval[i] = 22;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	intval[i] = 12;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (pqueue_insert(&pqueue, &intval[i]) != 0)
	   return 1;
	print_pqueue(&pqueue);
	i++;

	while (pqueue_size(&pqueue) > 0) {

	   fprintf(stdout, "Peeking at the highest priority element..Value=%03d\n",
	      *(int *)pqueue_peek(&pqueue));
	   if (pqueue_extract(&pqueue, (void **)&data) != 0)
	      return 1;
	   fprintf(stdout, "Extracting %03d\n", *(int *)data);
	   print_pqueue(&pqueue);

	}

	/*****************************************************************************
	*                                                                            *
	*  Destroy the priority queue.                                               *
	*                                                                            *
	*****************************************************************************/

	fprintf(stdout, "Destroying the pqueue\n");
	pqueue_destroy(&pqueue);

	return 0;
}
